import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../views/Login.vue'
import {initMenu} from "@/utils/menus";
import store from "@/store";
import {getRequest} from "@/utils/api";
import Home from "@/views/Home";
import FriendChat from "@/views/chat/FriendChat";
import AdminInfo from "@/views/AdminInfo";

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Login',
    component: Login,
    hidden:true
  },
    {
        path: '/home',
        name: 'Home',
        component: Home,
        children:[
            {
                path:'/chat',
                name: '在线聊天',
                component: FriendChat
            },
            {
                path:'/userinfo',
                name: '个人中心',
                component: AdminInfo
            }
        ]
    }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
    // 如果用户登录了，就初始化菜单
    if (window.sessionStorage.getItem("tokenStr")){
      initMenu(router, store);
      // 获取用户信息
      if (!window.sessionStorage.getItem('user')){
        return getRequest('/admin/info').then(resp =>{
            if (resp){
                window.sessionStorage.setItem('user', JSON.stringify(resp.obj));
                store.commit('INIT_ADMIN',resp.obj);
                next();
            }
        })
      }
      next();
    }else {
        // 如果这个请求是去登录页的就直接放行
        if (to.path == '/'){
            next();
        }else {
            // 如果不是去登录页的，就带上这个路径去跳转到登录页
            // 登陆成功后跳转到这个路径
            next('/?redirect='+to.path);
        }
    }
})

const originalPush = VueRouter.prototype.push
const originalReplace = VueRouter.prototype.replace
//push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
    if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
    return originalPush.call(this, location).catch(err => err)
}
//replace
VueRouter.prototype.replace = function push(location, onResolve, onReject) {
    if (onResolve || onReject) return originalReplace.call(this, location, onResolve, onReject)
    return originalReplace.call(this, location).catch(err => err)
}

export default router
